<?php
namespace app\api\service\delivery\shansong;

use app\api\service\delivery\PlatformInterface;
use app\api\service\delivery\shansong\ApiService;
use think\exception\ValidateException;
use app\api\model\Order;
use app\api\model\OrderShansong;
use app\api\model\Shop;
use app\api\model\SenderInfo;
use app\api\model\ReceiverInfo;
use app\api\model\Courier;
use think\facade\Db;
use think\facade\Log;
use app\api\model\MallDealLog;
use app\api\model\AppConfig;

// 闪送
class ShansongAdapter implements PlatformInterface
{

    public $ApiService;

    // 闪送状态码
    const STATUS_ERROR = 0;//失败
    const STATUS_SUCCESS = 200;//成功


    public static function statusList()
    {
        return [
            self::STATUS_ERROR => 'error',
            self::STATUS_SUCCESS => 'Success',
        ];
    }

    // 闪送订单状态
    const STATUS_ORDER_DISPATCH = 20;//派单中（转单改派中）
    const STATUS_ORDER_PICKUPING = 30;//待取货(已就位）
    const STATUS_ORDER_DELIVERY = 40;//闪送中(申请取消中、物品送回中、取消单客服介入中）
    const STATUS_ORDER_COMPLETED = 50;//已完成（已退款）
    const STATUS_ORDER_CANCELLED = 60;//已取消

    public static function statusOrderList()
    {
        return [
            self::STATUS_ORDER_DISPATCH => '派单中',
            self::STATUS_ORDER_PICKUPING => '待取货',
            self::STATUS_ORDER_DELIVERY => '配送中',
            self::STATUS_ORDER_COMPLETED => '已完成',
            self::STATUS_ORDER_CANCELLED => '已取消',
        ];
    }


    /*
    * $config: 配置信息
    * $pro_dev: true正式域名 false测试域名
    */
    public function __construct(array $config)
    {
        $this->ApiService=new ApiService($config);
    }


// ------------------------------------具体实现方法-----------------------------------



    // 1.查询开通城市
    public function openCitiesLists($params=[])
    {
        $res = $this->ApiService->sendUnite('openCitiesLists');

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $i=0;
            foreach($res["data"] as $arr){
                foreach($arr["cities"] as $v){
                    $data[$i]["cityCode"]=$v["code"];
                    $data[$i]["cityName"]=$v["name"];
                    $i++;
                }
            }
            $res["data"]=$data;
        }

        return $this->ApiService->returnUnite($res);
    }

    // 2.分页查询商户店铺
    public function queryAllStores($params=[])
    {
        try {
            validate([
                'pageNo'  => 'require', 
                'pageSize'  => 'require', 
                'pageSize'  => 'require', 
            ])->message([
                'pageNo.require'  => 'pageNo必须传递',   
                'pageSize.require'  => 'pageSize必须传递',   
                'pageSize.require'  => 'pageSize必须传递',   
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['storeName'] = $params['storeName'];
        $data['pageNo'] = $params['pageNo'];
        $data['pageSize'] = $params['pageSize'];
        $data = array_filter($data);

        $res = $this->ApiService->sendUnite('queryAllStores',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 4.查询城市可指定的交通工具
    public function optionalTravelWay($params=[])
    {
        try {
            validate([
                'cityId'  => 'require', 
            ])->message([
                'cityId.require'  => 'cityId必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['cityId'] = $params['cityId'];

        $res = $this->ApiService->sendUnite('optionalTravelWay',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 5.订单计费
    public function orderCalculate($params=[])
    {
        \think\facade\Log::info('闪送--订单计费--请求源参数--:' . json_encode($params));

        try {
            validate([
                'cityName'  => 'require', 
                'appointType'  => 'require', 
                'sender'  => 'require', 
                'receiverList'  => 'require', 
                'storeId'  => 'require', 
                'callNumber'  => 'require', //闪送请求不需要
            ])->message([
                'cityName.require'  => 'cityName必须传递',   
                'appointType.require'  => 'appointType必须传递',   
                'sender.require'  => 'sender必须传递',   
                'receiverList.require'  => 'receiverList必须传递',   
                'storeId.require'  => 'storeId必须传递',   
                'callNumber.require'  => 'callNumber必须传递',   
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        // 高德坐标转百度坐标
        $sender_map= gaode_to_baidu($params['sender']['fromLongitude']??'',$params['sender']['fromLatitude']??'');
        $receiver_map= gaode_to_baidu($params['receiverList']['toLongitude']??'',$params['receiverList']['toLatitude']??'');
        $params['sender']['fromLongitude']=$sender_map['lng'];//发件经度
        $params['sender']['fromLatitude']=$sender_map['lat'];//发件纬度
        $params['receiverList']['toLongitude']=$receiver_map['lng'];//收件经度
        $params['receiverList']['toLatitude']=$receiver_map['lat'];//收件纬度
     
        $postData['cityName'] =  $params['cityName']??'';//城市名称
        $postData['appointType']  =$params['appointType']??'';//预约类型
        $postData['appointmentDate']  = $params['appointmentDate']??'';//预约时间
        $postData['storeId']  = $params['storeId']??'';//配送店铺ID
        $postData['storeName']  = $params['storeName']??'';//店铺名
        $postData['travelWay'] = $params['travelWay']??'';//指定交通工具
        $postData['deliveryType'] = $params['deliveryType']??'';//1.帮我送 2.帮我取 ；默认为1
        $postData['pickupPwd'] = $params['pickupPwd']??'';//取件码开关
        $postData['deliveryPwd']  = $params['deliveryPwd']??'';//收件码开关
        $postData['lbsType']  = $params['lbsType']??'';//坐标类型(0：百度坐标系，1：国测局标准坐标系，非必填；默认为0)
        $postData['sender']  = $params['sender']??'';//发件人信息

        $receive=$params['receiverList'];
        $receiverList['orderNo']=$params['callNumber']??'';;
        $receiverList['toAddress']=$params['receiverList']['toAddress']??'';
        $receiverList['toLatitude']=$params['receiverList']['toLatitude']??'';
        $receiverList['toLongitude']=$params['receiverList']['toLongitude']??'';
        $receiverList['toReceiverName']=$params['receiverList']['toReceiverName']??'';
        $receiverList['toMobile']=$params['receiverList']['toMobile']??'';

        $receiverList['goodType']=$params['goodType']??'';
        $receiverList['weight']=$params['weight']??'';

        $expect_finish_time_limit= $params["expectEndTime"]??'';//期望送达时间（单位秒）
        $expect_finish_time_limit?$receiverList['expectEndTime']=$params['expectEndTime']*1000:'';

        $postData['receiverList']  =  [$receiverList];//收件人信息(列表)


        \think\facade\Log::info('闪送--订单计费--请求参数---:' . json_encode($params));
        // dump($postData);exit;

        // 请求闪送
        $res = $this->ApiService->sendUnite('orderCalculate',$postData);
        \think\facade\Log::info('闪送--订单计费--请求结果---:' . json_encode($res));
        // dump($res);exit;

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $appid=$params['appid'];//appid
            $app_type=get_app_type_int($params['app_type']);//app_type
            $data=$res['data'];//请求返回结果
            $third_number=$data['orderNumber'];//配送单号
            $call_number=$params['callNumber'];//调用方单号


            $appoint_type= $params["appointType"]??"";//0-即时发单；1-预约发单
            $appointment_date= $params["appointmentDate"]??"";//预约发单时间
            $expect_receive_time= $params['receiverList'][0]["expectEndTime"]??"";//期望送达时间
            $store_id= $params["storeId"]??"";//配送店铺id

            // 新增总订单(总表 金额单位统一：分)
            $orderData['appid'] = $appid;
            $orderData['third_number'] = $third_number;
            $orderData['call_number'] =  $call_number;
            $orderData['app_type'] = $app_type;

            $orderData['appoint_type'] = $appoint_type;//0:立即单, 1:预约单
            $orderData['appointment_date'] = $appointment_date;//预约取件时间
            $orderData['expect_receive_time'] = $expect_receive_time;//期望送达时间
            $orderData['store_id'] = $store_id;//配送店铺ID
            
            $orderData['total_distance'] = $data['totalDistance'] ?? 0;//总距离，单位：米
            $orderData['total_weight'] = $data['totalWeight'] ?? 0;//总重量，单位：kg
            $orderData['total_amount'] = $data['totalAmount'] ?? 0;//订单总金额，单位：分
            $orderData['coupon_save_fee'] = $data['couponSaveFee'] ?? 0;//优惠的总额度，单位：分
            $orderData['dynamic_subsidy_amount'] = $data['dynamicSubsidyAmount'] ?? 0;//限时补贴的费用，单位：分
            $orderData['total_fee_after_save'] = $data['totalFeeAfterSave'] ?? 0;//实际支付的费用，单位：分
            $add_order = (new Order)->orderCreate($orderData);

            $sys_number=$add_order['data']['sys_number'];//骑手系统订单号

            // 新增闪送订单(闪送 金额单位统一：分)
            $ssOrderData['appid'] = $appid;
            $ssOrderData['third_number'] = $third_number;
            $ssOrderData['sys_number'] = $sys_number;
            $ssOrderData['call_number'] =  $call_number;
            $ssOrderData['app_type'] = $app_type;

            $ssOrderData['appoint_type'] = $appoint_type;//0:立即单, 1:预约单
            $ssOrderData['appointment_date'] = $appointment_date;//预约取件时间
            $ssOrderData['store_id'] = $store_id;//配送店铺ID

            $ssOrderData['total_distance'] = $data['totalDistance'] ?? 0;
            $ssOrderData['total_weight'] = $data['totalWeight'] ?? 0;
            $ssOrderData['total_amount'] = $data['totalAmount'] ?? 0;
            $ssOrderData['coupon_save_fee'] = $data['couponSaveFee'] ?? 0;
            $ssOrderData['dynamic_subsidy_amount'] = $data['dynamicSubsidyAmount'] ?? 0;
            $ssOrderData['total_fee_after_save'] = $data['totalFeeAfterSave'] ?? 0;
            $ssOrderData['expect_receive_time'] = $expect_receive_time;
            $ssOrderData['estimate_grab_second'] = $data['estimateGrabSecond'] ?? 0;
            $ssOrderData['estimate_receive_second'] = $data['estimateReceiveSecond'] ?? 0;
            $ssOrderData['fee_info_list'] = !empty($data['feeInfoList']) ? json_encode($data['feeInfoList']) : '';
            $ssOrderData['interest_dto_list'] = !empty($data['interestDtoList']) ? json_encode($data['feeInfoList']) : '';

            $ssOrderData['good_type'] = $params['goodType'] ?? '';
            $ssOrderData['weight'] = $params['weight'] ?? '';
            $ssOrderData['remarks'] = $params['remarks'] ?? '';
            $ssOrderData['addition_fee'] = $params['additionFee'] ?? 0;
            $ssOrderData['ordering_source_type'] = $params['orderingSourceType'] ?? 0;
            $ssOrderData['ordering_source_no'] = $params['orderingSourceNo'] ?? '';
            $ssOrderData['goods_size_id'] = $params['goodsSizeId'] ?? 0;
            $ssOrderData['goods_price'] = $params['goodsPrice'] ?? 0;
            $ssOrderData['quality_delivery'] = $params['qualityDelivery'] ?? 0;
            $ssOrderData['insurance'] = $params['insurance'] ?? 0;
            $ssOrderData['insurance_pro_id'] = $params['insuranceProId'] ?? 0;
            $ssOrderData['insurance_flag'] = $params['insuranceFlag'] ?? 0;
            $ssOrderData['expect_start_time'] = $params['expectStartTime'] ?? '';
            $ssOrderData['expect_end_time'] = $params['expectEndTime'] ?? '';

            $add_ss_order = (new OrderShansong)->ssOrderCreate($ssOrderData);
            
            // 新增发件人
            $senderData['appid'] = $appid;
            $senderData['third_number'] = $third_number;
            $senderData['sys_number'] = $sys_number;
            $senderData['call_number'] = $call_number;
            $senderData['app_type'] =  $app_type;

            $senderData['from_address'] = $params['sender']['fromAddress'] ?? '';
            $senderData['from_address_detail'] = $params['sender']['fromAddressDetail'] ?? '';
            $senderData['from_sender_name'] = $params['sender']['fromSenderName'] ?? '';
            $senderData['from_mobile'] = $params['sender']['fromMobile'] ?? '';
            $senderData['from_latitude'] =$params['sender']['fromLatitude'] ?? '';
            $senderData['from_longitude'] =$params['sender']['fromLongitude'] ?? '';

            $add_sender = (new SenderInfo)->senderCreate($senderData);

            // 新增收件人
            $receiverData['appid'] = $appid;
            $receiverData['third_number'] =$third_number;
            $receiverData['sys_number'] =$sys_number;
            $receiverData['call_number'] =$call_number;
            $receiverData['app_type'] =  $app_type;

            $receive=$params['receiverList']??[];
            $receiverData['to_address'] = $receive['toAddress'] ?? '';
            $receiverData['to_address_detail'] = $receive['toAddressDetail'] ?? '';
            $receiverData['to_latitude'] =$receive['toLatitude']??'';
            $receiverData['to_longitude'] = $receive['toLongitude']??'';
            $receiverData['to_receiver_name'] = $receive['toReceiverName'] ?? '';
            $receiverData['to_mobile'] = $receive['toMobile'] ?? '';

            $add_receiver = (new ReceiverInfo)->receiverCreate($receiverData);

            // Db::startTrans();
            // try {

            //     $add_ss_order = (new OrderShansong)->save($ssOrderData);
            //     $add_sender = (new SenderInfo)->senderCreate($senderData);
            //     $add_receiver = (new ReceiverInfo)->receiverCreate($receiverData);

            //     Db::commit();
            // }catch (ValidateException $e) {
            //      Db::rollback();
            // }
            
            if($add_order['success']){
                $result_data=[
                    "totalDistance"=>$orderData['total_distance'] ,//总距离(米)
                    "totalWeight"=>$orderData['total_weight'] ,//总重量(kg)
                    "sysNumber"=>$sys_number,//系统单号
                    "totalAmount"=> $orderData['total_amount'],//订单总金额(分)
                    "couponSaveFee"=> $orderData['coupon_save_fee'],//优惠的总额度(分)
                    "totalFeeAfterSave"=>$orderData['total_fee_after_save'] ,//实际支付的费用(分)
                    "order_type"=>'shansong'
                ];

               return result_success('success',$result_data);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 6.提交订单
    public function orderPlace($params=[])
    {

        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        if(strpos($params['app_type'],'pro')){//正式下单
            // 验证余额
            $deal_balance=(new MallDealLog)->where('appid',$params['appid'])->order('id desc')->value('deal_balance');
            if($deal_balance < 3000){
                return result_error('余额不足30元,无法下单');
            }
        }

        $order_status = (new Order)->where('third_number',$params['issOrderNo'])->value('status');
        if($order_status!=0){
            return result_error('已下单，请勿重复下单');
        }


        $data['issOrderNo'] = $params['issOrderNo']??'';
        \think\facade\Log::info('闪送--提交订单--请求参数---:' . json_encode($data));

        $res = $this->ApiService->sendUnite('orderPlace',$data);
        \think\facade\Log::info('闪送--提交订单--请求结果---:' . json_encode($res));

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            // 更新总表订单状态
            $orderData['third_number']=$params['issOrderNo'];
            $orderData['status']=self::STATUS_ORDER_DISPATCH;//待接单
            $update_order = (new Order)->orderUpdate($orderData);

            // 更新闪送订单状态
            $ssOrderData['third_number']=$params['issOrderNo'];
            $ssOrderData['status']=self::STATUS_ORDER_DISPATCH;//待接单
            $update_ss_order = (new OrderShansong)->ssOrderUpdate($ssOrderData);


            if(strpos($params['app_type'],'pro')){//正式下单
                $appid =  $params['appid'] ?? '';
                $deal_type =  get_app_type_int($params['app_type']) ?? '';
                $order_id = $update_order['data']['id']??"";
                $sys_number = $update_order['data']['sys_number']??"";
                $deal_money = $update_order['data']['total_fee_after_save']??"";
                $deal_type_str ="闪送下单扣费";

                // 增加扣除账户余额日志
                $dealLogData['appid'] = $appid;//appid
                $dealLogData['deal_type'] =  $deal_type;//交易类型 {radio} (10:闪送, 20:达达,30:蜂鸟,-1充值)
                $dealLogData['order_id'] = $order_id;//order_id
                $dealLogData['sys_number'] = $sys_number;//系统单号
                $dealLogData['deal_money'] = $deal_money;//交易金额，单位：分
                $dealLogData['deal_type_str'] =$deal_type_str;//交易类型说明
                $dealLogData['remark'] ='';//备注
                $add_deal_log=(new MallDealLog)->dealLogCreate($dealLogData);
                if(!$add_deal_log['success']){
                  return result_error($add_deal_log['msg']??"余额扣费失败");
                }

                // 扣除账户余额
                $appConfigData['appid'] =$appid;//appid
                $appConfigData['money'] =$deal_money ;//money
                $doBalance=(new AppConfig)->doBalance($appConfigData,-1);

               return result_success('success',[]);
            }
        }
    }

    // 7.订单加价
    public function addition($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
                'additionAmount'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'additionAmount.require'  => 'additionAmount必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $call_number = (new Order)->where('third_number',$params['issOrderNo'])->value('call_number');
        if(!$call_number){
            output_error('未查询到订单');
        }

        $postData['issOrderNo']= $params['issOrderNo'];
        $postData['additionAmount']  =$params['additionAmount'];
 
        $saveData['third_number'] = $params['issOrderNo'];
        $saveData['addition_amount'] =  $params['additionAmount'];
        \think\facade\Log::info('闪送--订单加价--请求参数---:' . json_encode($postData));
        // var_dump($postData);exit;

        $res = $this->ApiService->sendUnite('addition',$postData);
        \think\facade\Log::info('闪送--订单加价--请求结果---:' . json_encode($res));
        // var_dump($res);exit;


        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $add = $Order->additionSave($saveData);

            $Order = new OrderShansong();
            $add = $Order->ssAdditionSave($saveData);
            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 8.查询订单详情
    public function orderInfo($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'thirdOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'thirdOrderNo.require'  => 'thirdOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['thirdOrderNo'] =  $params['thirdOrderNo'];

        $res = $this->ApiService->sendUnite('orderInfo',$data);

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $data=$res['data'];

            // 骑手信息
            $courier['name']=$data['courier']['name']??'';//骑手姓名
            $courier['mobile']=$data['courier']['mobile']??'';//骑手电话
            $gaode_map =baidu_to_gaode($data['courier']['longitude']??'', $data['courier']['latitude']??'');//(百度转高德)
            $courier['longitude']=$gaode_map['lng']??'';//骑手经度
            $courier['latitude']=$gaode_map['lat']??'';//骑手纬度
            $courier['headIcon']=$gaode_map['headIcon']??'';//骑手头像

            $result = [
                "orderStatus"=>$data['orderStatus'],//订单状态
                "orderStatusDesc"=>$data['orderStatusDesc'],//订单状态描述
                "courier"=>$courier,//骑手信息
                "totalAmount"=>$data['totalAmount'],//订单总金额
                "couponSaveFee"=>$data['couponSaveFee'],//总优惠额度
                "totalFeeAfterSave"=>$data['totalFeeAfterSave']//实付金额
            ];

            return result_success('success', $result);
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 9.查询闪送员位置信息
    public function courierInfo($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];

        $res = $this->ApiService->sendUnite('courierInfo',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 10.查询订单续重加价金额
    public function calculateOrderAddWeightFee($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'weight'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'weight.require'  => 'weight必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['weight'] = $params['weight'];

        $res = $this->ApiService->sendUnite('calculateOrderAddWeightFee',$data);
       
        return $this->ApiService->returnUnite($res);
    }

    // 11.支付订单续重费用
    public function payAddWeightFee($params=[])
    {
         try {
            validate([
                'issOrderNo'  => 'require', 
                'payAmount'  => 'require', 
                'weight'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',    
                'payAmount.require'  => 'payAmount必须传递',    
                'weight.require'  => 'weight必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['payAmount'] = $params['payAmount'];
        $data['weight'] = $params['weight'];
      
        $res = $this->ApiService->sendUnite('payAddWeightFee',$data);
       
        return $this->ApiService->returnUnite($res);
    }

    // 12.订单预取消
    public function preAbortOrder($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
     
        $res = $this->ApiService->sendUnite('preAbortOrder',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 13.订单取消
    public function abortOrder($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
                'deductFlag'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
                'deductFlag.require'  => 'deductFlag必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['deductFlag'] = $params['deductFlag'];

        $res = $this->ApiService->sendUnite('abortOrder',$data);


        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $Order = new Order();
            $orderUpdate['third_number'] = $data['issOrderNo'];
            $orderUpdate['status'] = self::STATUS_ORDER_CANCELLED;
            $add = $Order->orderUpdate($orderUpdate);

            $OrderShanSong = new OrderShansong();
            $orderUpdate['third_number'] = $data['issOrderNo'];
            $orderUpdate['status'] = self::STATUS_ORDER_CANCELLED;
            $add = $OrderShanSong->ssOrderUpdate($orderUpdate);

            if($add['success']){
                //返回骑手订单扣费deductFee：扣除费，sendBackFee：退回费
                $resData['deductFee']=$res['data']['deductAmount'];
                $resData['sendBackFee'] = $res['data']['sendBackFee'];
               return result_success('success',$resData);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 14.确认物品送回
    public function confirmGoodsReturn($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',           
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];

        $res = $this->ApiService->sendUnite('confirmGoodsReturn',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 15.新增店铺，16.修改店铺
    public function storeOperation($params=[])
    {
        try {
            validate([
                'storeName'  => 'require', 
                'cityName'  => 'require', 
                'address'  => 'require', 
                'addressDetail'  => 'require', 
                'latitude'  => 'require', 
                'longitude'  => 'require', 
                'phone'  => 'require', 
                'goodType'  => 'require', 
                'operationType'  => 'require', 
                'platformStoreId'  => 'require', 
            ])->message([
                'storeName.require'  => 'storeName必须传递',           
                'cityName.require'  => 'cityName必须传递',           
                'address.require'  => 'address必须传递',           
                'addressDetail.require'  => 'addressDetail必须传递',           
                'latitude.require'  => 'latitude必须传递',           
                'longitude.require'  => 'longitude必须传递',           
                'phone.require'  => 'phone必须传递',           
                'goodType.require'  => 'goodType必须传递',           
                'operationType.require'  => 'operationType必须传递',           
                'platformStoreId.require'  => 'platformStoreId必须传递',           
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        //新增店铺时，如果有，直接返回
        if ($params['operationType'] == 1) {
            $whereShop['appid']=$params['appid'];
            $whereShop['platform_store_id']=$params['platformStoreId'];
            $whereShop['app_type']=$params['app_type'];
            $find_shop=Shop::where($whereShop)->find();
            if($find_shop){
                $retDate['storeId']=$find_shop['store_id'];
                return result_success('success',$retDate);
            }
        }

        //修改店铺需要传递店铺ID
        if ($params['operationType'] == 2){
            if (empty($params['storeId'])){
               output_error('更新店铺时店铺ID不能为空');
            }
            $postData['storeId'] =   $saveData['store_id'] =  $params['storeId']??'';
        }

        // 高德坐标转百度坐标
        $baidu_map= gaode_to_baidu($params['longitude']??'',$params['latitude']??'');

        // 请求数据
        $postData['storeName']  = $params['storeName'];
        $postData['cityName'] = $params['cityName'];
        $postData['address']  = $params['address'];
        $postData['addressDetail'] = $params['addressDetail'];
        $postData['latitude']  = $baidu_map['lat'];//经度
        $postData['longitude']  = $baidu_map['lng'];//纬度
        $postData['phone']  = $params['phone'];
        $postData['goodType']  = $params['goodType'];
        $postData['operationType']  = $params['operationType'];// 默认值为1创建店铺，2更新店铺

        // 入库数据
        $saveData['store_name'] = $params['storeName'];
        $saveData['city_name'] = $params['cityName'];
        $saveData['address'] = $params['address'];
        $saveData['address_detail'] = $params['addressDetail'];
        $saveData['latitude'] = $params['latitude'];//经度
        $saveData['longitude'] = $params['longitude'];//纬度
        $saveData['phone'] = $params['phone'];
        $saveData['good_type'] = $params['goodType'];
        $saveData['operation_type'] = $params['operationType'];// 默认值为1创建店铺，2更新店铺
        
       
        $postData = array_filter($postData);
        \think\facade\Log::info('闪送--店铺操作--请求参数---:' . json_encode($postData));

        $res = $this->ApiService->sendUnite('storeOperation',$postData);
        \think\facade\Log::info('闪送--店铺操作--请求结果---:' . json_encode($res));


        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            if ($params['operationType'] == 1){//新增
                $Order = new Shop();
                $saveData['store_id'] = $res['data'];// $res['data']
                $saveData['appid'] =  $params['appid'];
                $saveData['app_type'] =get_app_type_int($params['app_type']);
                $saveData['platform_store_id'] =  $params['platformStoreId'];
                $saveData['contact_name'] =  $params['contactName']??'';
                $saveData['pro_dev'] =get_pro_dev_int($params['app_type']);
                $add = $Order->shopCreate($saveData);
            }else{//修改
                $Order = new Shop();
                $saveData['contact_name'] =  $params['contactName']??'';
                $add = $Order->shopUpdate($saveData);
            }

            if($add['success']){
               return result_success('success',['storeId'=>$res['data']]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 17.查询账号额度
    public function getUserAccount($params=[])
    {
        $res = $this->ApiService->sendUnite('getUserAccount');

        return $this->ApiService->returnUnite($res);
    }

    // 18.订单状态回调
    public function statusNotify($param=[])
    {
        if(empty($param['issOrderNo'])){
            \think\facade\Log::error("订单号为空:".json_encode($param));
            return json_encode(["status"=>self::STATUS_ERROR,"msg"=>"","data"=>null]);
        }
        $where[] = ['third_number', '=', $param['issOrderNo']];
        if (!empty($param['orderNo'])){
            $where[] = ['call_number', '=', $param['orderNo']];
        }
        $orderdetail =Order::where($where)->order('id', 'desc')->find();
        $appid = $orderdetail['appid'] ?? '';
        if (!empty($appid)){
            $notify_url = Db::name("app_interface_config")
                ->where('appid', $appid)
                ->value('rider_notify');
        }

        if (empty($notify_url)){
            \think\facade\Log::error("回调地址不存在:".json_encode($param));
            return json_encode(["status"=>self::STATUS_ERROR,"msg"=>"","data"=>null]);
        }
        $param['third_number'] = $orderdetail['third_number'] ?? '';//第三方配送平台订单号
        $param['sys_number'] = $orderdetail['sys_number'] ?? '';//系统订单号(系统生成)
        $param['call_number'] = $orderdetail['call_number'] ?? '';//调用方订单号
        $param['appid'] = $orderdetail['appid'] ?? '';//appid
        $param['app_type'] = $orderdetail['app_type'] ?? 0;

        //更新配送员消息
        if (!empty($param['courier'])){
            $Courier = new Courier();
            $courierParam = $param['courier'];
            $courierParam['third_number'] = $orderdetail['third_number'] ?? '';//第三方配送平台订单号
            $courierParam['sys_number'] = $orderdetail['sys_number'] ?? '';//系统订单号(系统生成)
            $courierParam['call_number'] = $orderdetail['call_number'] ?? '';//调用方订单号
            $courierParam['appid'] = $orderdetail['appid'] ?? '';//appid
            $courierParam['app_type'] = $orderdetail['app_type'] ?? 0;
            $courierParam = camelToSnake($courierParam);
            $courier_res = $Courier->courierSave($courierParam);
            if(!$courier_res["success"]){
                \think\facade\Log::error("闪送配送员保存失败:".json_encode($courierParam)."闪送订单更新结果:".json_encode($courier_res));
            }
        }
        //更新订单基本信息
        $Order = new Order();
        $orderParam = camelToSnake($param);
        if (!empty($courier_res["data"])){
            $orderParam['courier_id'] = $courier_res["data"];
        }
        $res_order = $Order->orderUpdate($orderParam);
        if(!$res_order["success"]){
            \think\facade\Log::error("闪送订单基本信息保存失败:".json_encode($orderParam)."闪送订单基本信息更新结果:".json_encode($res_order));
        }
        //更新闪送订单表
        $OrderShansong = new OrderShansong();
        $res_order_shangsong = $OrderShansong->ssOrderUpdate($orderParam);
        if(!$res_order_shangsong["success"]){
            \think\facade\Log::error("闪送订单更新失败:".json_encode($orderParam)."闪送订单更新结果:".json_encode($res_order_shangsong));
        }

        //转发到终端平台
        $param = snakeToCamel($param);
        $res = curl_post($notify_url, $param);
        $res = json_decode($res,1);

        $msg = !empty($res) && isset($res['msg']) ? $res['msg'] : '';
        if (empty($res) || empty($res['status'])) {
            return json_encode(["status"=>self::STATUS_ERROR,"msg"=>$msg,"data"=>null]);
        }
        return json_encode(["status"=>self::STATUS_SUCCESS,"msg"=>$msg,"data"=>null]);
    }

    // 19.修改收件人手机号
    public function updateToMobile($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
                'thirdOrderNo'  => 'require', 
                'newToMobile'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
                'thirdOrderNo.require'  => 'thirdOrderNo必须传递',       
                'newToMobile.require'  => 'newToMobile必须传递',            
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
        $data['thirdOrderNo'] = $params['thirdOrderNo'];
        $data['newToMobile'] = $params['newToMobile'];
     
        $res = $this->ApiService->sendUnite('updateToMobile',$data);

        if(isset($res['status'])&&$res['status']==self::STATUS_SUCCESS){
            $ReceiverInfo = new ReceiverInfo();
            $saveData['third_number'] = $data['issOrderNo'];//配送单号
            $saveData['to_mobile'] = $data['newToMobile'];//手机号
            $add = $ReceiverInfo->receiverUpdate($saveData);

            if($add['success']){
                return result_success('success',[]);
            }else{
                return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 
    }

    // 20.批量新增店铺
    public function addStores($params=[])
    {
        $storeList = request()->post('data/a',[],'strip_tags,htmlspecialchars');

        foreach ($storeList as &$v){
           $baidu_map= gaode_to_baidu($v['longitude']??'',$v['latitude']??'');// 高德坐标转百度坐标
           $v['latitude']=$baidu_map['lat'];
           $v['longitude']=$baidu_map['lng'];
        }
        
        $platformStoreIdArr=[];
        foreach ($storeList as $v){
           if(!isset($v['storeName'])||!isset($v['cityName'])||!isset($v['address'])||!isset($v['addressDetail'])||!isset($v['latitude'])||!isset($v['longitude'])||!isset($v['phone'])||!isset($v['goodType'])){
                return result_error('请求业务参数不全');
           }
           $platformStoreIdArr[$v['storeName'].$v['phone']]=$v['platformStoreId']??'';
        }

        $res = $this->ApiService->sendUnite('addStores',$storeList);

        $saveData = [];
        $appid=$params['appid'];
        $app_type=get_app_type_int($params['app_type']);

        if(isset($res['status']) && $res['status']==self::STATUS_SUCCESS && isset($res['data']['successList'])){
            foreach ($res['data']['successList'] as $store){
                $dto = $store['dto'];
                $storeId = $store['storeId'];

                $saveData[$storeId]['appid'] = $appid;
                $saveData[$storeId]['app_type'] =$app_type;
                $saveData[$storeId]['store_id'] =$store['storeId'];
                $saveData[$storeId]['platform_store_id'] =$platformStoreIdArr[$dto['storeName'].$dto['phone']];
                $saveData[$storeId]['store_name'] = $dto['storeName'];
                $saveData[$storeId]['city_name'] = $dto['cityName'];
                $saveData[$storeId]['address'] = $dto['address'];
                $saveData[$storeId]['address_detail'] =$dto['addressDetail'];
                $gaode_map=baidu_to_gaode($dto['longitude'],$dto['latitude']);// 百度坐标转高德坐标
                $saveData[$storeId]['latitude'] = $gaode_map['lat'];
                $saveData[$storeId]['longitude'] = $gaode_map['lng'];
                $saveData[$storeId]['contact_name'] = '';
                $saveData[$storeId]['phone'] = $dto['phone'];
                $saveData[$storeId]['pro_dev'] = get_pro_dev_int($params['app_type']);
                $saveData[$storeId]['good_type'] =$dto['goodType'];
            }

            $shop = new Shop();
            $add = $shop->shopListSave($saveData);

            if($add['success']){
               return result_success('success',[]);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
             return result_error($res["msg"]??'请求失败');
        }
    }

    // 21.查询订单ETA
    public function orderEta($params=[])
    {
        try {
            validate([
                'cityId'  => 'require', 
                'fromLat'  => 'require', 
                'fromLng'  => 'require', 
                'toLat'  => 'require', 
                'toLng'  => 'require', 
            ])->message([
                'cityId.require'  => 'cityId必须传递',       
                'fromLat.require'  => 'fromLat必须传递',       
                'fromLng.require'  => 'fromLng必须传递',       
                'toLat.require'  => 'toLat必须传递',       
                'toLng.require'  => 'toLng必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['cityId'] = $params['cityId'];
        $data['fromLat'] = $params['fromLat'];
        $data['fromLng'] = $params['fromLng'];
        $data['toLat'] = $params['toLat'];
        $data['toLng'] = $params['toLng'];
     
        $res = $this->ApiService->sendUnite('orderEta',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 22.订单追单
    public function appendOrder($params=[])
    {
        try {
            validate([
                'sysNumber'  => 'require',
                'appendsysNumber'  => 'require',
            ])->message([
                'sysNumber.require'  => 'sysNumber必须传递',       
                'appendsysNumber.require'  => 'appendsysNumber必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['orderNumber'] = $params['sysNumber'];
        $appendsysNumber=Order::where('sys_number',$params['appendsysNumber'])->value('call_number');
        $data['appendOrderNumber'] = $params['appendsysNumber'];
     
        $res = $this->ApiService->sendUnite('appendOrder',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 23.查询是否支持尊享送
    public function qualityDeliverySwitch($params=[])
    {
        try {
            validate([
                'cityName'  => 'require', 
            ])->message([
                'cityName.require'  => 'cityName必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['cityName'] = $params['cityName'];
     
        $res = $this->ApiService->sendUnite('qualityDeliverySwitch',$data);

        return $this->ApiService->returnUnite($res);
    }

    // 24.查询尊享送达成状态
    public function qualityDeliveryStatus($params=[])
    {
        try {
            validate([
                'issOrderNo'  => 'require', 
            ])->message([
                'issOrderNo.require'  => 'issOrderNo必须传递',       
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
        $data['issOrderNo'] = $params['issOrderNo'];
     
        $res = $this->ApiService->sendUnite('qualityDeliveryStatus',$data);

        return $this->ApiService->returnUnite($res);
    }


    public function merchantExamine(array $params){return result_error("闪送不支持查此状态");}//商户审核骑士取消订单
    public function transporter(array $params){return result_error("闪送不支持查此状态");}//获取骑士配送信息H5页面
    public function afterSale(array $params){return result_error("闪送不支持查此状态");}//商户确认售后单交接完成
    public function fetchCode(array $params){return result_error("闪送不支持查此状态");}//更新取件码和货架号
    public function cancelReasons($params){return result_error("闪送不支持查此状态");}//订单取消原因
    public function complaint($params){return result_error("闪送不支持查此状态");}//商家投诉
    public function complaintReasons($params){return result_error("闪送不支持查此状态");}//商家投诉原因

}